/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.takeeasy.platform.facade.servlet;

import com.takeeasy.platform.cache.ConfigCache;
import com.takeeasy.platform.config.ConfigParser;
import com.takeeasy.platform.exception.ConfigFileParseException;
import com.takeeasy.platform.persistence.ConnectionPool;
import java.util.Map;
import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author 景龙
 */
public class StartManager {

    private static final Logger logger = LoggerFactory.getLogger(StartManager.class);

    public void startUpPlatform() {
        ConfigParser parser = new ConfigParser();
        try {
            parser.loadConfig();
            initPlatform();
        } catch (ConfigFileParseException e) {
            throw new RuntimeException(e);
        }
    }

    private void initPlatform() {
        initDataBaseConnectionPool();
        ConnectionPool.testConnection();
        ActionLoader actionLoader = new ActionLoader();
        actionLoader.load();
    }

    private void initDataBaseConnectionPool() {
        logger.debug("创建数据库连接池...");
        Map<String, String> databaseConfig = ConfigCache.config.get(ConfigCache.CONFIG_DATABASE);
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName(databaseConfig.get(ConfigCache.DATABASE_CLASSNAME));
        bds.setUrl(databaseConfig.get(ConfigCache.DATABASE_URL));
        bds.setUsername(databaseConfig.get(ConfigCache.DATABASE_USERNAME));
        bds.setPassword(databaseConfig.get(ConfigCache.DATABASE_PASSWORD));
        bds.setMaxIdle(Integer.parseInt(databaseConfig.get(ConfigCache.DATABASE_MAXIDLE)));
        bds.setMaxActive(Integer.parseInt(databaseConfig.get(ConfigCache.DATABASE_MAXACTIVE)));
        bds.setMaxWait(Long.parseLong(databaseConfig.get(ConfigCache.DATABASE_MAXWAIT)));
        ConnectionPool.setDataSource(bds);
    }
}
